package com.application.chiettinhdienluc.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.adapter.DanhMucTramAdapter;
import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.db.TramDataSource;
import com.application.chiettinhdienluc.model.TramModel;
import com.application.chiettinhdienluc.rsclient.DataConnDetector;
import com.application.chiettinhdienluc.rsclient.RsGetClient;


public class DanhMucTramActivity extends SherlockFragmentActivity implements
android.view.View.OnClickListener {

	private Resources res;
	private ListView danh_muc_tram_lv;
	DanhMucTramAdapter dataAdapter;
	private final int ID_ACTION_SAVE = 1;
	private ArrayList<TramModel> list_tram = new ArrayList<TramModel>();
	private TramDataSource nd = new TramDataSource();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.danh_muc_tram_listview);
		res = getResources();

		ActionBar actionbar = getSupportActionBar();

		if (actionbar != null) {
			actionbar.setTitle(res.getString(R.string.str_title_viewlist_tram));
			actionbar.setDisplayHomeAsUpEnabled(true);
			actionbar.setDisplayShowHomeEnabled(true);

		}
		danh_muc_tram_lv = (ListView) findViewById(R.id.danh_muc_tram_lv);
		// chiettinhListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		dataAdapter = new DanhMucTramAdapter(DanhMucTramActivity.this, list_tram);
		danh_muc_tram_lv.setAdapter(dataAdapter);

		loadDanhMucTram();
	}

	private void loadDanhMucTram() {
		if (list_tram != null)
			list_tram.clear();

		list_tram = nd.loadTram();
		dataAdapter.setItemList(list_tram);
		dataAdapter.notifyDataSetChanged();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		switch (itemId) {
		case android.R.id.home:
			finish();
			break;
		case ID_ACTION_DOWNLOAD:

			DataConnDetector detector = new DataConnDetector(
					MainApplication.getAppContext());
			if (detector.isConnectingToInternet()) {
				getDanhMucTram();
			} else {
				Toast.makeText(MainApplication.getAppContext(),
						R.string.no_connection_message, Toast.LENGTH_SHORT)
						.show();

			}

			break;

		}
		return super.onOptionsItemSelected(item);
	}
	
	
private ProgressDialog progressBar ;
	
	private void getDanhMucTram() {

		try {	
			
			progressBar = new ProgressDialog(this);
			progressBar.setMessage(res.getString(R.string.str_tram_download_waiting));
			progressBar.setIndeterminate(true);
			progressBar.setCancelable(false);
			progressBar.show();
	
			RsGetDanhMucTramCountTask task = new RsGetDanhMucTramCountTask();
			task.execute();

		} catch (Exception e) {
			e.printStackTrace();

		}

	}
	
	private String pageCountResponse = "";
	private int itemCount = 0;

	private class RsGetDanhMucTramCountTask extends
			AsyncTask<String, Void, Void> {

		@Override
		protected Void doInBackground(String... params) {		

			
			RsGetClient jParser = new RsGetClient();
			// http://192.168.1.46:46685
			String baseUrl = MainApplication.getServerURL();
			String url = baseUrl + "/ctrs/resources/danhmuctram/"
					+ MainApplication.getMaDonViQuanLy();

			pageCountResponse = jParser.getValueFromUrl(url);

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			
		
			if (!pageCountResponse.isEmpty())
				itemCount = Integer.parseInt(pageCountResponse.trim());

			Log.i("So luong tram", itemCount + "");
			int pageCount = itemCount / 50;

			if (itemCount % 50 > 0)
				pageCount++;

			newTramList.clear();
			
			if(pageCount >= 1) {
				for (int i = 1; i < pageCount + 1; i++) {
	
					Log.i("Get danh muc tram", i + "");
					RsGetDanhMucTramTask task = new RsGetDanhMucTramTask();
					task.execute(i + "");
				}
			}
			else
			{
				progressBar.dismiss();
				Toast.makeText(MainApplication.getAppContext(),
					res.getString(R.string.str_tram_download_finish),
					Toast.LENGTH_SHORT).show();
			
			}
		}
		
		
		@Override
        protected void onPreExecute() {
		
        	
        }
 
        @Override
        protected void onProgressUpdate(Void... values) {
            //Log.i(TAG, "onProgressInsert");
        	
        	
        }

	}
	
	JSONArray messages = null;
	JSONObject json = null;
	ArrayList<HashMap<String, String>> messageList = null;

	private class RsGetDanhMucTramTask extends AsyncTask<String, Void, Void> {

		@Override
		protected Void doInBackground(String... params) {

			RsGetClient jParser = new RsGetClient();
			// http://192.168.1.46:46685
			String baseUrl = MainApplication.getServerURL();
			String url = baseUrl + "/ctrs/resources/danhmuctram/"
					+ MainApplication.getMaDonViQuanLy() + "/" + params[0];

			messages = jParser.getJSONFromUrl(url);

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			addDanhMucTram();

		}

	}

	private List<TramModel> newTramList = new ArrayList<TramModel>();

	protected void addDanhMucTram() {

		try {

			int j = 1;
			// looping through All Contacts
			for (int i = 0; i < messages.length(); i++) {

				JSONObject c = messages.getJSONObject(i);

				TramModel tr = new TramModel();

				tr.setMaDonViQuanLy(c.getString("maDviqly"));
                tr.setMaTram(c.getString("maTram"));  
                tr.setTenTram(c.getString("tenTram"));                 
                tr.setDinhDanh(c.getString("dinhDanh"));  
                tr.setLoaiTram(c.getString("loaiTram"));  
                
                tr.setCongSuatTram(c.getLong("csuatTram"));
                tr.setMaCapDA(c.getString("maCapda"));  
                tr.setMaCapDaRa(c.getString("maCapdaRa"));  
               
                tr.setMaTo(c.getString("maTo"));  
                tr.setTinhTrang(c.getInt("tinhTrang")); 
                
                tr.setHoSoPhu(c.getInt("hsPhu"));  
               

				newTramList.add(tr);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		if(newTramList.size() ==itemCount) {
			storeDanhMucTram(newTramList);
		}
		
		
		//progressBar.setProgress(newVatTuList.size());
		 
		Log.i("Update Danh muc tram", newTramList.size() + "");
	}


	protected void storeDanhMucTram(List<TramModel> newTramList) {

		TramDataSource dataSource = new TramDataSource();

		int j = 1;
		// looping through All Contacts
		for (int i = 0; i < newTramList.size(); i++) {

			TramModel tr = newTramList.get(i);

			boolean existed = false;

			existed = dataSource.checkTramExist(tr.getMaTram(),
					tr.getMaDonViQuanLy());

			if (!existed) {

				long id = dataSource.insert(tr);
			} else {
				dataSource.update(tr);
				Log.i("Update Tram ", i + "");
			}

		}
		        
		progressBar.dismiss();
		
		loadDanhMucTram();

		Toast.makeText(MainApplication.getAppContext(),
				res.getString(R.string.str_tram_download_finish),
				Toast.LENGTH_SHORT).show();

	}

	
	
	private final int OPTIONMENU_MENU_MAIN = 0;
	private final int ID_ACTION_DOWNLOAD = OPTIONMENU_MENU_MAIN + 1;

	private final short ORDER_POS_FIRST = 1;
	private final short ORDER_POS_SECOND = ORDER_POS_FIRST + 1;
	
	
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);

		if (res == null)
			return false;
		try {
			if (menu != null) {
				menu.close();
				menu.clear();
			}

			/*
			SubMenu submenu = menu.addSubMenu(OPTIONMENU_MENU_MAIN,
					OPTIONMENU_MENU_MAIN, ORDER_POS_SECOND ,
					res.getString(R.string.main_tab_hint_btn_menu));
					*/

		

			menu.add(OPTIONMENU_MENU_MAIN, ID_ACTION_DOWNLOAD, ORDER_POS_FIRST,
					res.getString(R.string.str_tram_download))
					.setIcon(R.drawable.download_icon)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

			//MenuItem menuItem = submenu.getItem();
			//menuItem.setIcon(R.drawable.abs__ic_menu_moreoverflow_normal_holo_dark);
			//menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

			return true;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//menu.add(Menu.NONE, ID_ACTION_SAVE, Menu.NONE, "Save").setIcon(R.drawable.content_save).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
	
		return true;
	}
	
	@Override
	public void onBackPressed() {
		finish();
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}

}
